﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class Data
{
    public MaintainData maintainData;
    public CompensateDiamondData compensateData;
    public WhiteListData whiteListData;
}



public class Game : LifeCycle, IClientsManagerListener
{
    static Game _instance;
    public static Game instance
    {
        get
        {
            if (_instance == null)
                _instance = new Game();

            return _instance;
        }
    }

    Data m_Data;
    public Data data
    {
        get
        {
            if (m_Data == null)
                m_Data = new Data();

            return m_Data;
        }
    }

    TCPClientsManager m_ClientsSocket;
    public TCPClientsManager clientsSocket => m_ClientsSocket;

    ConnectPingController m_ConnectPingController;

    UserServerCollection m_Users = new UserServerCollection();
    public UserServerCollection userCollection => m_Users;

    ServerConnectController m_ServerConnectCtrl;

    /// <summary>
    /// 与匹配服务器的连接
    /// </summary>
    public TCPRemote connectWithMatch;

    /// <summary>
    /// 与闲逛服务器的连接
    /// </summary>
    public TCPRemote connectWithWalk;

    /// <summary>
    /// 与战斗服务器的连接
    /// </summary>
    public TCPRemote[] battleConnects = new TCPRemote[0];

    /// <summary>
    /// 是否正在连接战斗服
    /// </summary>
    //bool[] m_InConnectWithBattle;

    //object connectWithBattleBaton = new object();

    /// <summary>
    /// 是否使用独立匹配服
    /// </summary>
    public static bool SeparateMatchServer = false;
    
    Server m_ServerParam;
    public Server serverParam
    {
        get
        {
            if (m_ServerParam == null)
            {
                m_ServerParam = Server.ReadServerConfig();
            }

            return m_ServerParam;
        }
    }

    IDecode m_RSADecoder;

    Server m_IpConfig;


    int m_CurBattleServerIndex;
    protected long GetCurBattleServerIndex()
    {
        return System.Threading.Interlocked.Increment(ref m_CurBattleServerIndex);
    }
//#if IOSReview
//    const bool ConnectPingUdp = false;
//#else
    const bool ConnectPingUdp = true;
//#endif

    public void GameStart()
    {
        TryCreateDatabase();
        //DropAndCreateUserDatabase();

        LoadConstData();

        this.Start(5);

        m_ServerConnectCtrl = new ServerConnectController();

        m_RSADecoder = InitDecoder();
        m_ClientsSocket = new TCPClientsManager(InitEncoder(), m_RSADecoder);

        m_ClientsSocket.Start(serverParam.logicServerPortForClient, 65534);
        m_ClientsSocket.listener = this;

        this.AddLifeCycle(m_ClientsSocket);

        m_ConnectPingController = new ConnectPingController();
        m_ConnectPingController.Start(ConnectPingUdp, serverParam.connectPingPort);

        m_ConnectMasterCtrl = new ServerConnectController();
        m_IpConfig = Server.ReadServerConfig();
        m_ConnectMasterCtrl.Start(m_IpConfig.logicServerPortForMaster, 5, OnServerConnected);

        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
        AsyncHttpRequest.TrustInvalidCertificate(true);

        //ThreadPool.SetMinThreads(1, 1);
        //ThreadPool.SetMaxThreads(5, 5);
        //for (int i = 1; i <= 10; i++)
        //{
        //    ThreadPool.QueueUserWorkItem(new WaitCallback(testFun), i.ToString());
        //}
        //Console.WriteLine("主线程执行！");
        //Console.WriteLine("主线程结束！");
        //Console.ReadKey();
    }

    //public void testFun(object obj)
    //{
    //    Console.WriteLine(string.Format("{0}:第{1}个线程,当前线程为{2}",
    //    DateTime.Now.ToString(), obj.ToString(),
    //    Thread.CurrentThread.ManagedThreadId.ToString()));
    //    Thread.Sleep(1000);
    //}

    static void TryCreateDatabase()
    {
        //Shared
        bool newCreate = MysqlFunction.CreateDatabaseIfNotExist(ServerConfig.DBShared);
        GameDebug.Log($"尝试创建数据库：{ServerConfig.DBShared} newCreate：{newCreate}");
        if (newCreate)
        {
            string sql = System.IO.File.ReadAllText(ServerConfig.DBSharedSqlPath);
            MysqlHelper.ExecuteSql(ServerConfig.DBShared, sql);
        }

        //user
        for (int i = 1; i <= ServerConfig.MaxDBUserID; i++)
        {
            string database = ServerConfig.DBUserBase + i;
            newCreate = MysqlFunction.CreateDatabaseIfNotExist(database);

            GameDebug.Log($"尝试创建数据库：{database} newCreate：{newCreate}");

            if (newCreate)
            {
                string sql = System.IO.File.ReadAllText(ServerConfig.DBUserSqlPath);
                MysqlHelper.ExecuteSql(database, sql);
            }
        }
    }

    static void DropAndCreateUserDatabase()
    {
        for (int i = 1; i <= ServerConfig.MaxDBUserID; i++)
        {
            string database = ServerConfig.DBUserBase + i;
            bool newCreate = MysqlFunction.CreateDatabaseIfNotExist(database);

            GameDebug.Log($"重建数据库：{database} newCreate：{newCreate}");

            string sql = System.IO.File.ReadAllText(ServerConfig.DBRecreateUserSqlPath);
            MysqlHelper.ExecuteSql(database, sql);

        }
    }
    public static IEncode InitEncoder()
    {
        return null;
    }

    //private const string AESKey = "123456789012345678901234567890pp";

    public static IDecode InitDecoder()
    {
       //AES256Encode decoder = new AES256Encode(AESKey);

        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

        string str_Private_Key = File.ReadAllText(ServerConfig.RSAPrivateKeyPath).Trim();

        RSA.ImportCspBlob(Convert.FromBase64String(str_Private_Key));

        var decoder = new RSAAndAES256(RSA.ExportParameters(true));

        return decoder;
    }

#region master

    ServerConnectController m_ConnectMasterCtrl;

    /// <summary>
    /// 与Master服务器的连接
    /// </summary>
    TCPRemote m_MasterServer;
    public TCPRemote masterlogicServer => m_MasterServer;


    NetMessageDispacher NewMessageDispacherForMaster()
    {
        NetMessageDispacher messageDispacher = new NetMessageDispacher();

        messageDispacher.RegisterHandler(NetHandler_KickOutUser.Key, NetHandler_KickOutUser.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_Maintain.Key, NetHandler_Maintain.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_Compensate.Key, NetHandler_Compensate.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_WhiteList.Key, NetHandler_WhiteList.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_DebugInfo.Key, NetHandler_DebugInfo.NewHandler);

        return messageDispacher;
    }
    public void OnServerConnected(EndPoint endPoint, Socket connect)
    {
        GameDebug.Log("连接上Master服务器");

        TCPSocketServer connectRemote = new TCPSocketServer(connect);

        m_MasterServer = new TCPRemote(0, connectRemote, OnDisconnect);
        m_MasterServer.messageDispacher = NewMessageDispacherForMaster();

        m_MasterServer.BeginReceive();
    }

    private void OnDisconnect(TCPRemote obj)
    {
        GameDebug.Log("与Master服连接断开");
    }

    public void SendToMasterServer(NetSendToServer netSend, Action<string> onConnectedFailed)
    {
        if (m_MasterServer == null || !m_MasterServer.connected)
        {
            onConnectedFailed?.Invoke("未连接到Master服务");
        }
        else
        {
            netSend.SendToRemote(m_MasterServer);
        }

    }
#endregion

    public static string GetIpWithIpAddress(IPAddress iPAddress)
    {
        return ServerUtility.GetIpWithIpAddress(iPAddress);
    }


    //void OnUserOffline(TCPClient client)
    //{
    //    GameDebug.Log($"用户离线:{client.userID}");

    //    if (client.userID > 0)
    //    {
    //        users.UpdateLastOfflineTime(client.userID, CommonFunctions.GetTimeStampSeconds());
    //    }
    //}

    public UserServer AddUser(string uuid, TCPClient client, User userData,double loginTime,double lastOfflineTime)
    {
        //var exist = m_Users.FindUser(data.id);
        //if(exist != null)
        //{
        //    GameDebug.Log($"用户重新激活 userId ：{exist.data.id}  new clientId:{client.clientId}");

        //    exist.client = client;
        //    m_ClientsSocket.OnAddLoginedUser(exist.data.id, client);
        //    return exist;
        //}

        UserServer user = new UserServer();
        user.data = userData;
        user.uuid = uuid;
        user.client = client;
        user.loginTime = loginTime;
        user.lastOfflineTime = lastOfflineTime;
        
        GameDebug.Log($"登入用户  user id ：{user.data.id}  client.userID:{client.userID}  clientId:{client.clientId}");
        m_ClientsSocket.OnAddLoginedUser(user.data.id, client);

        m_Users.AddUser(user);

        return user;
    }

    public UserServer GetUser(TCPClient client)
    {
        return GetUser(client.userID);
    }

    public UserServer GetUser(long userId)
    {
        return m_Users.FindUser(userId);
    }
    
    /// <summary>
    /// 开始新游戏
    /// </summary>
    public void LoadConstData()
    {
        ///初始化常量数据
        ConstDataManager.Instance.Init();

        Localization.instance.GetType();

        if (ConstData.Instance != null)
        {
            GameDebug.Log("加载常量数据成功");

            //GameDebug.Log($"提示有：{ConstData.Instance.tips.GetArrStr() }");
            //GameDebug.Log($"角色有：{ConstData.Instance.pets.GetArrStr()}");
            //GameDebug.Log($"皮肤有：{ConstData.Instance.skins.GetArrStr()}");
            //GameDebug.Log($"道具有：{ConstData.Instance.props.GetArrStr()}");
             GameDebug.Log($"商品有：{ConstData.Instance.goods.GetArrStr() }");
           // GameDebug.Log($"AI Config  1 aiAttackDefenseRate:{ConstData.Instance.GetAIConfigWithLevel(1).aiAttackDefenseRate}");
        }
    }

    

#region INetServerListener
    /// <summary>
    /// 新建数据分发器
    /// </summary>
    /// <returns></returns>
    NetMessageDispacher NewMessageDispacher()
    {
        NetMessageDispacher messageDispacher = new NetMessageDispacher();

        //messageDispacher.RegisterEvent("NetRequest_Hello", NetHandler_Hello.NewHandler);
        messageDispacher.RegisterHandler("NetRequest_Ping", NetHandler_Ping.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_Login.Login_Key, NetHandler_Login.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_BaseInfo.Key, NetHandler_BaseInfo.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_DetailInfo.Key, NetHandler_DetailInfo.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_UpdateIntroduction.Key, NetHandler_UpdateIntroduction.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_UploadPhoto.Key, NetHandler_UploadPhoto.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_FetchCandidates.Key, NetHandler_FetchCandidates.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_Apply.Key, NetHandler_Apply.NewHandler); 
        messageDispacher.RegisterHandler(NetHandler_UpdateApply.Key, NetHandler_UpdateApply.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_Dialogue.Key, NetHandler_Dialogue.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_FetchUserInfos.Key, NetHandler_FetchUserInfos.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_GetUserMomentsInfos.Key, NetHandler_GetUserMomentsInfos.NewHandler); 
        messageDispacher.RegisterHandler(NetHandler_FetchMiniUserInfos.Key, NetHandler_FetchMiniUserInfos.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_PaymentValidate.PaymentValidate_Key, NetHandler_PaymentValidate.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_UpdateRequirement.Key, NetHandler_UpdateRequirement.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_Visit.Key, NetHandler_Visit.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_Like.Key, NetHandler_Like.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_Follow.Key, NetHandler_Follow.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_FetchMoments.Key, NetHandler_FetchMoments.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_AddMoment.Key, NetHandler_AddMoment.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_LikeMoment.Key, NetHandler_LikeMoment.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_LikeComment.Key, NetHandler_LikeComment.NewHandler);
        messageDispacher.RegisterHandler(NetHandler_AddComment.Key, NetHandler_AddComment.NewHandler);

        return messageDispacher;
    }

    public void OnNewClient(Remote client)
    {
        client.messageDispacher = NewMessageDispacher();
    }

    public void OnDisConnect(Remote client)
    {
        RemoveUser(client);

        GameDebug.Log($"用户离线:{client.userID}  {client.ipEndPoint}");

        if (client.userID > 0)
        {
            users.UpdateLastOfflineTime(client.userID, CommonFunctions.GetTimeStampSeconds());
        }

    }
    
    public void RemoveUser(Remote client)
    {
        TCPClient user = client as TCPClient;
        if (user != null)
            this.m_Users.RemoveUser(user.userID, user.ipEndPoint);
        else
            GameDebug.LogError($"user == null client:{client.GetType().Name}  client == null:{client == null}");
    }

#endregion


    protected override void _Update()
    {
        //if (curFrame > 0 && curFrame % (this.m_FPS * 5) == 0)
        //{
        //    lock (battleConnects)
        //    {
        //        for (int i = 0; i < battleConnects.Length; i++)
        //        {
        //            if (!m_InConnectWithBattle[i])
        //            {
        //                if (battleConnects[i] == null || !battleConnects[i].connected)
        //                {
        //                    ConnectToBattleServer(null, battleConnects[i]);
        //                }
        //            }
        //        }
        //    }
        //}
        //lock (battleConnects)
        //{
        //    foreach (var connect in battleConnects)
        //    {
        //        if (connect != null && connect.messageDispacher != null)
        //        {
        //            connect.messageDispacher.Update();
        //        }
        //    }
        //}

//#if DEBUG
//        if (curFrame % (this.m_FPS * 5) == 0)
//        {
//            try
//            {
//                string requestBody = GetDebugInfo();

//                //GameDebug.Log($"Logic 发送数据：{requestBody}");

//                string url = $"https://localhost:1901/debuginfo/logic_server_info";

//                var request = WebRequest.Create(url) as HttpWebRequest;
//                request.ProtocolVersion = HttpVersion.Version11;
//                request.Timeout = 5000;
//                request.Method = "POST";
//                request.ContentType = "application/json";
//                var postData = Encoding.ASCII.GetBytes(requestBody);
//                request.ContentLength = postData.Length;

//                using (var postStream = request.GetRequestStream())
//                {
//                    postStream.Write(postData, 0, postData.Length);
//                }
//                request.GetResponse();
//            }
//            catch (Exception e)
//            {
//                GameDebug.LogError(e.Message + "\n" + e.StackTrace);
//            }
//        }
//#endif

    }

    public LogicServerInfo GetDebugInfo()
    {
        LogicServerInfo logicServerInfo = new LogicServerInfo();

        logicServerInfo.onlineUsers = this.m_Users.users.Map(e => new LogicServerUserInfo()
        {
            id = e.Value.data.id,
            clientId = e.Value.client.clientId,
            nick  =e.Value.data.nick,
            uuid = e.Value.data.token,
            diamond = e.Value.data.diamond,
            lv = e.Value.data.level,
        }).AsList();

       /* logicServerInfo.matchingRooms = MatchController.instance.normalMatchRooms.Map(e => new RoomInfo
        {
            battleId = e.roomId,
            team1 = e.team1Datas.Map(u=>new RoomUserInfo() { id = u.userId,nick = this.GetUser(u.userId)?.data?.nick,power = u.power,roleId = u.roleId}).AsList(),
            team2 = e.team2Datas.Map(u => new RoomUserInfo() { id = u.userId, nick = this.GetUser(u.userId)?.data?.nick, power = u.power, roleId = u.roleId }).AsList()
        }).AsList();*/

        return logicServerInfo;
    }


    ///// <summary>
    ///// 连接匹配服务器
    ///// </summary>
    //public void ConnectToMatchServer(Action onEnd)
    //{
    //    if (SeparateMatchServer)
    //    {
    //        m_ServerConnectCtrl.Connect(serverParam.matchServerAddress, serverParam.matchServerPortForLogic,
    //            (connect) =>
    //            {
    //                GameDebug.Log("连接到匹配服务器");

    //                TCPSocketServer serverSocket = new TCPSocketServer(connect);

    //                connectWithMatch = new TCPRemote(serverSocket, OnDisconnectWithMatchServer);

    //                connectWithMatch.messageDispacher = new NetMessageDispacher();
    //                connectWithMatch.messageDispacher.RegisterHandler(NetServerHandler_MatchRoomUsers.MatchRoomUsers_Key, NetServerHandler_MatchRoomUsers.NewHandler);

    //                //connectWithMatch.BeginReceive();

    //                onEnd?.Invoke();
    //            }, 
    //            (error) =>
    //            {
    //                GameDebug.LogError(error);
    //                onEnd?.Invoke();
    //            }
    //            );
    //    }
    //    else
    //    {
    //        MatchController.instance.Start(defaultFPS);
    //        MatchController.instance.onMatchUserCome = this.OnMatchUserCome;
    //        MatchController.instance.onMatchSuc = this.OnMatchSuc;
    //    }
    //}

    //void OnDisconnectWithMatchServer(TCPRemote connectWithMatch)
    //{
    //    GameDebug.LogError("与匹配服断开连接");

    //    ConnectToMatchServer(null);
    //}

    //public void OnMatchUserCome(string roomId, List<UserJoinMatchData> matchUsers)
    //{
    //    SendMatchRoomUsersEvent(roomId, matchUsers, false);
    //}

    //public void OnMatchUserLeave(MatchRoom room)
    //{
    //    SendMatchRoomUsersEvent(room.roomId, room.userJoinMatchDatas, false);
    //}
    //public void OnMatchSuc(MatchRoom room)
    //{
    //    SendMatchRoomUsersEvent(room.roomId, room.userJoinMatchDatas, true);
    //}

    //void SendMatchRoomUsersEvent(string roomId, List<UserJoinMatchData> matchUsers, bool roomFull)
    //{
    //    MatchRoomUsersData usersData = new MatchRoomUsersData();
    //    usersData.roomFull = roomFull;
    //    usersData.users = matchUsers;
    //    usersData.roomId = roomId;

    //    NetServerHandler_MatchRoomUsers.OnServerMatchRoomUsers(usersData);
    //}

    ///// <summary>
    ///// 匹配成功，请求战斗服务器
    ///// </summary>
    //public void OnMatchSuc(List<UserServer> users, MatchRoomInfo matchRoomData)
    //{
    //    ///向战斗服务器发请求
    //    NetSend_BattleMatchRoom netSend = new NetSend_BattleMatchRoom();

    //    TCPRemote battleServer = DispatchBattleServer(matchRoomData.roomId, out int index);

    //    string battleServerIp = "";

    //    battleServerIp = m_IpConfig.battleServerAddress[index];

    //    //if (m_IpConfig.battleServerAddress.Length == 1)
    //    //{
    //    //    battleServerIp = m_IpConfig.battleServerAddress[0];
    //    //}
    //    //else
    //    //{
    //    //    battleServerIp = m_IpConfig.battleServerAddress[index]; //GetIpWithIpAddress(battleServer.ipEndPoint.Address);
    //    //}
    //    matchRoomData.battleServerIp = battleServerIp;

    //    netSend.matchRoomData = matchRoomData;
    //    netSend.onResponse = (responseData) =>
    //    {
    //        BattleMatchRoomResponseData battleMatchRoom = responseData as BattleMatchRoomResponseData;
    //        if (battleMatchRoom != null && battleMatchRoom.code == 0)
    //        {
    //            GameDebug.Log($"战斗准备开始  戰鬥服IP：{battleServerIp} :{battleMatchRoom.battleMatchRoom.matchUsers.GetListStr()}");

    //            NetEvent_BattleStart battleStart = new NetEvent_BattleStart();
    //            battleStart.matchRoomInfo = battleMatchRoom.battleMatchRoom;

    //            users.ForEach((u) =>
    //            {
    //                u.UpdateBattleTimes(u.data.battleTimes + 1);

    //                if (u.matchInfo != null)
    //                    u.matchInfo.matchSuc = true;

    //                u.battleResultInfo = null;

    //                u.battleInfo = new BattleInfo();
    //                u.battleInfo.ip = battleServerIp;
    //                u.battleInfo.port = m_IpConfig.battleServerPortForClient;
    //                u.battleInfo.mapId = matchRoomData.mapId;
    //                u.battleInfo.roomId = matchRoomData.roomId;
    //            });

    //            users.ForEach((u) =>
    //            {
    //                battleStart.SendToRemote(u.client);
    //            });
    //        }
    //        else
    //        {
    //            GameDebug.LogError($"请求战斗出错 ：{battleMatchRoom == null}  {responseData?.err}  {responseData?.code} roomId:{matchRoomData.roomId}");

    //            OnSendBattleUsersFailed(users, $"请求战斗出错：{responseData.err}   roomId:{matchRoomData.roomId}");
    //        }
    //    };

    //    netSend.onTimeOut = (req) =>
    //    {
    //        GameDebug.LogError($"战斗请求超时:{matchRoomData.roomId}");
    //        OnSendBattleUsersFailed(users, $"战斗请求超时:{matchRoomData.roomId}");

    //        ConnectToBattleServer(null, battleServer);
    //    };

    //    SendToBattleServer(netSend, (err) =>
    //    {
    //        if (!string.IsNullOrEmpty(err))
    //        {
    //            OnSendBattleUsersFailed(users, err);
    //        }
    //    }, matchRoomData.roomId, battleServer);
    //}

    //void OnSendBattleUsersFailed(List<UserServer> users, string error)
    //{
    //    GameDebug.LogError($"发送匹配失败:{error}");

    //    NetEvent_MatchRoomInfo netEvent_MatchRoom = new NetEvent_MatchRoomInfo();
    //    netEvent_MatchRoom.matchRoomInfo = new MatchRoomInfo();

    //    users.ForEach((u) =>
    //    {
    //        netEvent_MatchRoom.SendToRemote(u.client);
    //    });
    //}
    ///// <summary>
    ///// 连接战斗服务器
    ///// </summary>
    //public void ConnectToBattleServer(Action onEnd, TCPRemote battleRemote = null)
    //{
    //   // m_InConnectWithBattle = true;

    //    if (battleRemote == null)
    //    {
    //        lock (battleConnects)
    //        {
    //            m_InConnectWithBattle = new bool[serverParam.battleServerAddress.Length];

    //            battleConnects = new TCPRemote[serverParam.battleServerAddress.Length];

    //            for (int i = 0; i < battleConnects.Length; i++)
    //            {
    //                int index = i;

    //                m_InConnectWithBattle[i] = true;

    //                if(Environment.OSVersion.Platform== PlatformID.Win32NT)
    //                {
    //                    if( serverParam.battleServerAddress[i] != Server.GetLocalIP()
    //                        && serverParam.battleServerAddress[i] != "115.29.67.138")
    //                    {
    //                        GameDebug.LogError($"win测试跳过：{serverParam.battleServerAddress[i]}");
    //                        continue;
    //                    }
    //                }
    //                m_ServerConnectCtrl.Connect(serverParam.battleServerAddress[i], serverParam.battleServerPortForLogic, (connect) =>
    //               {
    //                  TCPSocketServer serverSocket = new TCPSocketServer(connect);

    //                  lock (battleConnects)
    //                  {
    //                      battleConnects[index] = new TCPRemote(serverSocket, OnDisconnectWithBattleServer);

    //                      battleConnects[index].messageDispacher = new NetMessageDispacher();
    //                      battleConnects[index].messageDispacher.RegisterHandler(NetServerHandler_BattleResult.BattleResult_Key, NetServerHandler_BattleResult.NewHandler);

    //                      m_InConnectWithBattle[index] = false;

    //                      GameDebug.Log($"连接到战斗服务器,戰鬥服有：{battleConnects.GetArrStr()}");
    //                  }
    //                  onEnd?.Invoke();
    //              },
    //              (error) =>
    //              {
    //                  GameDebug.LogError($"連接失敗：{serverParam.battleServerAddress[index]}   "+error);
    //                  lock (battleConnects)
    //                  {
    //                      m_InConnectWithBattle[index] = false;
    //                  }

    //                  onEnd?.Invoke();
    //              });
    //            }
    //        }
    //    }
    //    else
    //    {
    //        GameDebug.LogError($"重連：{battleRemote.ipEndPoint.Address.ToString()},{Environment.StackTrace}");

    //        m_ServerConnectCtrl.Connect(GetIpWithIpAddress(battleRemote.ipEndPoint.Address), serverParam.battleServerPortForLogic, (connect) =>
    //        {
    //            TCPSocketServer serverSocket = new TCPSocketServer(connect);

    //            var newBattleRemote = new TCPRemote(serverSocket, OnDisconnectWithBattleServer);

    //            GameDebug.Log("连接到战斗服务器");

    //            newBattleRemote.messageDispacher = new NetMessageDispacher();
    //            newBattleRemote.messageDispacher.RegisterHandler(NetServerHandler_BattleResult.BattleResult_Key, NetServerHandler_BattleResult.NewHandler);

    //            lock (battleConnects)
    //            {
    //                int index = System.Array.IndexOf(this.battleConnects, battleRemote);
    //                if (index >= 0)
    //                {
    //                    m_InConnectWithBattle[index] = false;
    //                }


    //                battleConnects[index] = newBattleRemote;
    //            }

    //            onEnd?.Invoke();
    //        },
    //       (error) =>
    //       {
    //           GameDebug.LogError(error);

    //           onEnd?.Invoke();

    //           lock (battleConnects)
    //           {
    //               int index = System.Array.IndexOf(this.battleConnects, battleRemote);
    //               if (index >= 0)
    //               {
    //                   m_InConnectWithBattle[index] = false;
    //               }
    //           }
    //       });
    //    }
    //}
    //void OnDisconnectWithBattleServer(TCPRemote connectWithBattle)
    //{
    //    GameDebug.LogError("与战斗服断开连接");

    //    this.ConnectToBattleServer(null, connectWithBattle);
    //}

    //public void SendToMatchServer(NetSendToServer netSend)
    //{
    //    if (connectWithMatch == null || !connectWithMatch.connected)
    //    {
    //        ConnectToMatchServer(() =>
    //        {
    //            if (connectWithMatch == null)
    //            {
    //                GameDebug.LogError("连接到匹配服务器失败");
    //                return;
    //            }
    //            if (connectWithMatch.connected)
    //                netSend.SendToRemote(connectWithMatch);
    //            else
    //                GameDebug.LogError("发送失败,未连接到匹配服务器");

    //        });
    //    }
    //    else
    //    {
    //        netSend.SendToRemote(connectWithMatch);
    //    }
    //}

    //Dictionary<string, TCPRemote> battleIdServerDict = new Dictionary<string, TCPRemote>();

    //public void OnBattleResult(BattleResultData data)
    //{
    //    lock (battleIdServerDict)
    //    {
    //        battleIdServerDict.Remove(data.roomId);
    //    }
    //}

    ///// <summary>
    ///// 分配戰鬥服
    ///// </summary>
    ///// <param name="battleId"></param>
    ///// <returns></returns>
    //TCPRemote DispatchBattleServer(string battleId, out int index)
    //{
    //    TCPRemote connectBattle = null;

    //    lock (battleConnects)
    //    {
    //        index = (int)(GetCurBattleServerIndex() % this.battleConnects.Length);
    //        connectBattle = this.battleConnects[index];

    //        GameDebug.Log($"戰鬥：{battleId}  使用戰鬥服：{connectBattle.ipEndPoint}");
    //    }
    //    lock (battleIdServerDict)
    //    {
    //        battleIdServerDict[battleId] = connectBattle;
    //    }
    //    return connectBattle;
    //}

    //public void SendToBattleServer(NetSendToServer netSend, Action<string> onConnectedFailed, string battleId, TCPRemote connectWithBattle)
    //{
    //    if (connectWithBattle == null)
    //    {
    //        lock (battleIdServerDict)
    //        {
    //            if (battleIdServerDict.ContainsKey(battleId))
    //            {
    //                connectWithBattle = battleIdServerDict[battleId];
    //            }
    //            else
    //            {
    //                GameDebug.LogError($"battleIdServerDict not contains :{battleId}");
    //            }
    //        }
    //    }

    //    if (connectWithBattle == null || !connectWithBattle.connected)
    //    {
    //        ConnectToBattleServer(() =>
    //        {
    //            if (connectWithBattle == null)
    //            {
    //                GameDebug.LogError("连接到战斗服务器失败");
    //                onConnectedFailed?.Invoke("连接到战斗服务器失败");
    //                return;
    //            }

    //            Thread.Sleep(100);

    //            //Task delaySend =
    //            if (connectWithBattle.connected)
    //                netSend.SendToRemote(connectWithBattle);
    //            else
    //                onConnectedFailed?.Invoke("发送失败,未连接到战斗服务器");

    //        }, connectWithBattle);
    //    }
    //    else
    //    {
    //        //GameDebug.LogError($"SendToBattleServer  :{netSend.GetType().Name}  {netSend.GetHashCode()}");
    //        netSend.SendToRemote(connectWithBattle);
    //    }


    //}

    //public void SendToWalkServer(NetSendToServer netSend)
    //{
    //    if (connectWithWalk == null || !connectWithWalk.connected)
    //    {
    //        ConnectToWalkServer();
    //    }
    //    if (connectWithWalk == null)
    //    {
    //        GameDebug.LogError("连接到闲逛服务器失败");
    //        return;
    //    }
    //    if (connectWithWalk.connected)
    //        netSend.SendToRemote(connectWithWalk);
    //    else
    //        GameDebug.LogError("发送失败,未连接到闲逛服务器");
    //}
}

